package com.study.talk.ui.app.group.info

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.ArrayAdapter
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.study.talk.ui.app.base.BaseActivity
import com.study.talk.databinding.ActivityGroupInfoBinding
import com.study.talk.data.model.GroupInfo
import com.study.talk.netty.NettyClient
import com.study.talk.netty.message.request.ApplyGroupRequest
import com.study.talk.netty.message.response.ApplyGroupSelfResponse
import com.study.common.DateUtil
import com.study.talk.R
import com.study.talk.ui.adapter.GroupUsersAdapter
import com.study.talk.utils.alert.AlertUtil
import com.study.talk.utils.extras.getIntParam
import com.study.talk.utils.extras.showToast
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@AndroidEntryPoint
class GroupInfoActivity : BaseActivity() {

    companion object {
        private const val TAG = "GroupInfoActivity"
        const val DATA_NAME = "groupId"
    }

    private val vm: GroupInfoViewModel by viewModels()

    private val binding: ActivityGroupInfoBinding by lazy {
        DataBindingUtil.setContentView(
            this, R.layout.activity_group_info
        )
    }

    private val groupId by lazy { getIntParam(DATA_NAME) }

    private val groupMembersAdapter by lazy { GroupUsersAdapter(app.localUserId) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setSupportActionBar(binding.groupInfoToolbar)

        binding.vm = vm

        binding.lifecycleOwner = this

        binding.groupInfoUserListView.layoutManager = LinearLayoutManager(this)
        binding.groupInfoUserListView.adapter = groupMembersAdapter

        vm.groupDetails.observe(this) {
            initView(it)
        }

        vm.members.observe(this) {
            groupMembersAdapter.submitList(it)
        }

        vm.isMember.observe(this) {
            binding.groupInfoAddBt.text = when (it) {
                1 -> "退出群聊"
                2 -> "加入群聊"
                3 -> "解散群聊"
                4 -> "当前群聊已被解散无法操作"
                else -> "错误"
            }
        }

        vm.getGroupInfo(groupId)
    }


    @SuppressLint("SetTextI18n")
    private fun initView(group: GroupInfo) {

        binding.groupInfoToolbar.setNavigationOnClickListener { finish() }

        binding.groupInfoListView.adapter = ArrayAdapter(
            this@GroupInfoActivity, android.R.layout.simple_list_item_1, createListViewData()
        )

        binding.groupInfoAddBt.setOnClickListener { _ ->
            when (vm.isMember.value) {
                1 -> AlertUtil.showCustomDialog(
                    this@GroupInfoActivity, "退出群聊提醒", "确定要退出群聊吗？"
                ) { if (it) vm.exitGroup(groupId = group.id) }

                2 -> { //申请加入群聊
                    NettyClient.sendMessage(ApplyGroupRequest(group.id, DateUtil.currentTime()))
                }

                3 -> {
                    AlertUtil.showCustomDialog(
                        this@GroupInfoActivity, "操作提醒", "确定要解散该群聊吗?此操作不可恢复哦!"
                    ) { if (it) vm.disbandGroup(groupId = group.id) }
                }

                4 -> showToast("群聊已被解散，无法进行操作")
            }
        }
    }

    /** 申请加入群聊消息发送成功会根据EventBus的消息分发来到这 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAddUserSelfResponseMessage(response: ApplyGroupSelfResponse) {
        if (response.success) {
            showToast("加入群聊请求发送成功!")
        } else {
            showToast("发送失败:" + response.reason)
        }
    }

    private fun createListViewData(): List<String> {
        return mutableListOf<String>().apply {
            add("群聊标签：" + vm.groupDetails.value?.tag)
            add("群聊简介：" + vm.groupDetails.value?.introduce)
        }
    }
}